<template>
  <div class="scene-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">本地景点</h1>
      <p class="page-subtitle">亲近自然、发现您身边的美丽景点</p>
    </div>
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input v-model="searchQuery" placeholder="搜索景点名称..." size="large" clearable @input="handleSearch">
          <template #append>
            <el-icon @click="handleSearch" style="cursor: pointer"><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 筛选器 -->
      <div class="filters-row">
        <el-select v-model="selectedRating" placeholder="评分筛选" clearable @change="handleFilter" style="width: 120px">
          <el-option label="全部评分" value="" />
          <el-option label="5星" value="5" />
          <el-option label="4星以上" value="4" />
        </el-select>

        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort" style="width: 120px">
          <el-option label="综合排序" value="default" />
          <el-option label="评分最高" value="rating" />
          <el-option label="最新发布" value="newest" />
        </el-select>
      </div>
    </div>

    <div class="scene-cards" v-loading="loading">
      <el-empty v-if="list.length == 0" description="暂无数据" />
      <RouterLink :to="`/scene/detail?id=${item.id}`" v-for="(item, index) in list" target="_blank" :key="index">
        <div class="scene-card">
          <el-image :src="item.image" style="width: 100%; height: 200px" cover />
          <div>
            <h2 class="scene-title">{{ item.name }}</h2>
            <div class="scene-rating">
              <el-rate v-model="item.rating" />
              <span class="text-caption">{{ item.rating.toFixed(1) }}分</span>
            </div>
            <p class="scene-location">{{ item.location }}</p>
            <p class="scene-description text-sm">{{ item.description }}</p>
          </div>
          <div>
            <el-button @click.stop="showDetails(item)"> 查看详情 </el-button>
            <el-popconfirm title="你确定删除该数据" @confirm="handleRemove(item)" placement="top">
              <template #reference>
                <el-button type="warning" v-if="showAdminOpts" plain> 删除 </el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </RouterLink>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="prev, pager, next" :page-size="10" :total="totalCount" @change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { useHead } from '@vueuse/head'
import { fetchList, remove } from '@/apis/scene'
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const route = useRouter()

const showAdminOpts = computed(() => {
  return userStore.showAdminOpts ?? false
})

const handleRemove = (obj: any) => {
  // 处理删除逻辑
  remove(obj.id)
    .then((response) => {
      let { code, message } = response.data
      if (code !== 200) {
        throw new Error(message || '删除失败')
      }
      // 删除成功后重新获取数据
      fetchData()
    })
    .catch((error) => {
      console.error('删除失败:', error)
    })
}

useHead({
  title: '地方景点 - 探索本地美丽风景',
  meta: [{ name: 'description', content: '探索您所在地区的美丽景点，发现自然和文化的奇迹。' }]
})

const totalCount = ref(100) // 假设总职位数为1000
const searchQuery = ref('') // 搜索关键词
const listQuery = {
  page: 1,
  pageSize: 12,
  keyword: ''
}
const list = reactive<any>([])
const loading = ref(false)
const fetchData = () => {
  // 模拟获取数据
  listQuery.keyword = searchQuery.value.trim()
  loading.value = true
  fetchList(listQuery)
    .then((response) => {
      let { code, result, message } = response.data
      if (code !== 200) {
        throw new Error(message || '获取数据失败')
      }
      if (result.page) {
        list.splice(0, list.length) // 清空列表
      }
      totalCount.value = result.total
      for (let item of result.items) {
        let imgs = JSON.parse(item.imageUrls)
        item.image = imgs.length > 0 ? imgs[0] : 'https://picsum.photos/400/300?ght=200&width=300'
      }
      list.splice(0, 0, ...result.items)
      // console.log('获取到的数据:', list)
    })
    .catch((error) => {
      console.error('获取数据失败:', error)
    })
    .finally(() => {
      loading.value = false
    })
}

const handleCurrentChange = (page: number, pageSize: number) => {
  // 这里可以添加分页逻辑
  listQuery.page = page
  listQuery.pageSize = pageSize
  fetchData()
  // console.log(`当前页: ${page}, 每页条数: ${pageSize}`)
}

onMounted(() => {
  fetchData()
})

const handleSearch = () => {
  // 处理搜索和排序
  fetchData()
}

const sortBy = ref<string>('default')
const selectedCategory = ref<string>('')
const selectedRating = ref<string>('')
const selectedDistrict = ref<string>('')

const showDetails = (scene: any) => {
  route.push({
    path: `/scene/detail`,
    query: {
      id: scene.id,
      target: '_blank'
    }
  })
}

const handleFilter = () => {
  // 这里可以添加筛选逻辑
}
const handleSort = () => {
  // 这里可以添加排序逻辑
}
</script>

<style scoped>
.scene-list {
  max-width: var(--page-max-width);
  background-color: #f8fafc;
  padding: 20px;
  margin: 0px auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.page-header {
  width: 100%;
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2563eb;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 1.1rem;
  color: #6b7280;
  margin: 0;
}
.search-filter-section {
  width: 100%;
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.search-bar {
  margin-bottom: 20px;
}

.filters-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.scene-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  width: 100%;
}

.scene-card {
  cursor: pointer;
  background-color: #eee;
  padding: 20px;
  transition: transform 0.3s;
  border-radius: 10px;
}

.scene-card:hover {
  transform: translateY(-5px);
}

.scene-title {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 10px;
}

.scene-rating {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.scene-location {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 10px;
}

.scene-description {
  color: #888;
  margin-bottom: 15px;
  display: -webkit-box;
  color: #555;
  -webkit-line-clamp: 4; /* 限制2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>
